package com.jtpay.sdk.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.channel.test.tblUnifiedTimeStatistics;
import com.jtpay.sdk.R;
import com.jtpay.sdk.adapter.PayTypeAdapter;
import com.jtpay.sdk.jtpay.constant.PayConstant;
import com.jtpay.sdk.jtpay.constant.PayExceptionType;
import com.jtpay.sdk.jtpay.model.PayInfo;
import com.jtpay.sdk.jtpay.utils.PayLogUtil;
import com.jtpay.sdk.jtpay.PayUtil;
import com.jtpay.sdk.jtpay.listener.PayUtilListener;
import com.jtpay.sdk.model.TimerControlInfo;
import com.jtpay.sdk.util.GlobalUtil;
import com.jtpay.sdk.util.JFTMD5Utils;
import com.jtpay.sdk.util.JftConstants;
import com.jtpay.sdk.util.JftLogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import de.greenrobot.dao.AbstractDao;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class PayTypeActivity extends BaseActivity implements PayUtilListener {
    private PayUtil mPayUtil;
    private PayInfo mPayInfo;
    protected Dialog mProgressDialog;
    private Toast mToast;
    private TextView mNameText;
    private TextView mPriceText;
    private ListView mListView;
    private String mUserCode;
    private String mComKey;
    private String mHostName;
    private String mTitle;
    private String mPrice;
    private int mCheckedId = -1;
    private ImageView oldCheckedView;
    private Button mSubmitBtn;

    private TimerControlInfo mTimerControlInfo = new TimerControlInfo();
    private tblUnifiedTimeStatistics mTimeStatistics = new tblUnifiedTimeStatistics();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paytype);
        //数据库信息初始化
        setupDatabase();

        Intent intent = getIntent();
        if (null != intent) {
            Bundle bundle = intent.getExtras();
            mHostName = bundle.getString(JftConstants.JUN_FU_TONG_HOST_NAME);
            mUserCode = bundle.getString(JftConstants.JUN_FU_TONG_USER_CODE);
            mComKey = bundle.getString(JftConstants.JUN_FU_TONG_COM_KEY);
            mTitle = bundle.getString(JftConstants.JUN_FU_TONG_TITLE);
            mPrice = bundle.getString(JftConstants.JUN_FU_TONG_PRICE);
        }
        mPayUtil = GlobalUtil.getInstance().getPayUtil();
        mPayUtil.setActivity(this);
        mPayInfo = mPayUtil.getPayInfo();
        mPayInfo.setPaySystemId(mHostName);
        initViews();
        getToken();
    }

    /**
     * database  table tblUnifiedTimeStatistics operation
     */
    private AbstractDao getTblUnifiedTimeStatisticsDao() {
        return daoSession.getTblUnifiedTimeStatisticsDao();
    }

    private void insertTblUnifiedTimeStatistics(tblUnifiedTimeStatistics mTimeStatistics) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mTimeStatistics.setSystemTime(simpleDateFormat.format(new Date()));
        getTblUnifiedTimeStatisticsDao().insertOrReplace(mTimeStatistics);
    }

    public static void startActivity(Context context, String price, String userCode, String comKey, String hostName, String title) {
        Intent intent = new Intent(context, PayTypeActivity.class);
        intent.putExtra(JftConstants.JUN_FU_TONG_PRICE, price);
        intent.putExtra(JftConstants.JUN_FU_TONG_USER_CODE, userCode);
        intent.putExtra(JftConstants.JUN_FU_TONG_COM_KEY, comKey);
        intent.putExtra(JftConstants.JUN_FU_TONG_HOST_NAME, hostName);
        intent.putExtra(JftConstants.JUN_FU_TONG_TITLE, title);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPayUtil.removeTopListener();
    }

    private void initViews() {
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        mNameText = (TextView) findViewById(R.id.text_name);
        mPriceText = (TextView) findViewById(R.id.text_price);
        mListView = (ListView) findViewById(R.id.list_view);
        mNameText.setText(mTitle);
        mPriceText.setText(mPrice);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mCheckedId != -1) {
                    oldCheckedView.setImageResource(R.drawable.image_icon_radiobutton_no);
                }
                oldCheckedView = (ImageView) view.findViewById(R.id.ImageButton_junpay_type_Checked);
                oldCheckedView.setImageResource(R.drawable.image_icon_radiobutton_yes);
                mCheckedId = position;
            }
        });
        mSubmitBtn = (Button) findViewById(R.id.btn_submit);
        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedId >= 0) {
                    mPayInfo.setPayTypeId(mPayInfo.getPayTypeModels().get(mCheckedId).getTypeid());
                    mPayInfo.setPayTypeName(mPayInfo.getPayTypeModels().get(mCheckedId).getTypename());
                    showProgressDialog();
                    mPayUtil.getChannelList();
                } else {
                    Toast.makeText(PayTypeActivity.this, getString(R.string.pay_not_available), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            PayLogUtil.log("dismiss");
            mProgressDialog.dismiss();
        }
    }

    private void showToast(String str) {
        mToast.setText(str);
        mToast.show();
    }

    private TokenParam getTokenParam() {
        Date date = new Date();
        String p1_usercode = mUserCode; //user define
        String CompKey = mComKey;//user define
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String p2_order = dateFormat.format(date);
        String p3_money = mPriceText.getText().toString();
        String p4_returnurl = "http://shangjia.jtpay.com/Form/TestReturn"; //user define
        String p5_notifyurl = "http://shangjia.jtpay.com/Form/TestNotice"; //user define
        String p6_ordertime = dateFormat.format(date);
        String p7_sign = JFTMD5Utils.getMD5(p1_usercode + "&" + p2_order + "&" + p3_money + "&" + p4_returnurl + "&" + p5_notifyurl + "&" + p6_ordertime + CompKey).toUpperCase();
        return new TokenParam(p1_usercode, p2_order, p3_money, p4_returnurl, p5_notifyurl, p6_ordertime, "SDK", p7_sign);
    }

    private void getToken() {
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(PayConstant.TIME_OUT, TimeUnit.SECONDS).readTimeout(PayConstant.TIME_OUT, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(JftConstants.JUN_FU_TONG_URL).client(client).build();
        APIInterface apiInterface = retrofit.create(APIInterface.class);
        TokenParam tokenParam = getTokenParam();

        Map<String, String> map = new HashMap<>();
        map.put("p1_usercode", tokenParam.getUserCode());
        map.put("p2_order", tokenParam.getOrder());
        map.put("p3_money", tokenParam.getMoney());
        map.put("p4_returnurl", tokenParam.getReturnUrl());
        map.put("p5_notifyurl", tokenParam.getNotifyUrl());
        map.put("p6_ordertime", tokenParam.getOrderTime());
        map.put("p9_paymethod", tokenParam.getMethod());
        map.put("p7_sign", tokenParam.getSign());
        //  get token  start time
        mTimerControlInfo.setStartDate(new Date());

        retrofit2.Call<ResponseBody> resultCall =
                apiInterface.getToken(mHostName, map);
        resultCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, Response<ResponseBody> response) {
                JftLogUtil.log("get Token onResponse!");
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        JftLogUtil.log("result = " + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String flag = jsonObject.getString("flag");
                        if ("1".equals(flag)) {
                            String token = jsonObject.getString("token");
                            if (TextUtils.isEmpty(token)) {
                                JftLogUtil.log("Token is empty!");
                                return;
                            }
                            // get token  end time
                            mTimerControlInfo.setEndDate(new Date());
                            double tokenTime = getCostTime(mTimerControlInfo.getStartDate(),
                                    mTimerControlInfo.getEndDate());
                            mTimeStatistics.setTokenTime(String.valueOf(tokenTime));
                            mTimerControlInfo.DateInfoClear();

                            mPayInfo.setToken(token);
                            showProgressDialog();
                            // getType start time
                            mTimerControlInfo.setStartDate(new Date());
                            mPayUtil.getPayType();
                        } else if ("0".equals(flag)) {
                            String msg = jsonObject.getString("msg");
                            dismiss();
                            showToast(msg);
                        }
                    } catch (JSONException | IOException e) {
                        dismiss();
                        showToast(e.getMessage());
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                PayLogUtil.log("getToken onFailure");
            }
        });
    }

    public void onPayDataResult() {
        // getType end time
        mTimerControlInfo.setEndDate(new Date());
        double getTypeTime =getCostTime(mTimerControlInfo.getStartDate(),
                mTimerControlInfo.getEndDate());
        mTimeStatistics.setPaylistTime(String.valueOf(getTypeTime));
        runOnUiThread(mRunnable);
    }

    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            dismiss();
            if (mPayInfo.getPayTypeModels().size() > 0) {
                mListView.setVisibility(View.VISIBLE);
                PayTypeAdapter adapter = new PayTypeAdapter(PayTypeActivity.this, mPayInfo.getPayTypeModels());
                mListView.setAdapter(adapter);
                mListView.post(new Runnable() {
                    // set default choice
                    @Override
                    public void run() {
                        oldCheckedView = (ImageView) mListView.getChildAt(0).findViewById(R.id.ImageButton_junpay_type_Checked);
                        oldCheckedView.setImageResource(R.drawable.image_icon_radiobutton_yes);
                        mCheckedId = 0;

                    }
                });
            } else {
                mListView.setVisibility(View.GONE);
            }
            mTimeStatistics.setPlatform(mTitle);
            insertTblUnifiedTimeStatistics(mTimeStatistics);
        }
    };

    @Override
    public void onPayException(int exceptionType, String exceptionContent) {
        if (null != exceptionContent) {
            showToast(exceptionContent);
        } else {
            PayExceptionType type = PayExceptionType.values()[exceptionType];
            dismiss();
            String str;
            switch (type) {
                case DATA_EXCEPTION: {
                    str = getString(R.string.data_exception);
                    break;
                }
                case ENCRYPT_EXCEPTION: {
                    str = getString(R.string.encrypt_exception);
                    break;
                }
                case GET_PAY_METHOD_FAILED: {
                    str = getString(R.string.get_pay_method_failed);
                    break;
                }
                case DECRYPT_EXCEPTION: {
                    str = getString(R.string.decrypt_exception);
                    break;
                }
                case RETURN_ERROR_DATA: {
                    str = getString(R.string.return_error_data);
                    break;
                }
                case PAY_SYSTEM_ID_EMPTY: {
                    str = getString(R.string.pay_system_id_empty);
                    break;
                }
                case SERVER_CONNECTION_EXCEPTION: {
                    str = getString(R.string.server_connection_exception);
                    break;
                }
                default: {
                    str = "";
                    break;
                }
            }
            showToast(str);
        }
    }


    @Override
    public void onPayProgressDialog() {
        dismiss();
    }

    //add gettoken data
    @Override
    public void onShowChannelList() {
        Intent intent = new Intent(PayTypeActivity.this, ChannelActivity.class);
        intent.putExtra(JftConstants.JUN_FU_TONG_TITLE, mTitle);
        intent.putExtra(JftConstants.JUN_FU_TONG_USER_CODE, mUserCode);
        intent.putExtra(JftConstants.JUN_FU_TONG_COM_KEY, mComKey);
        intent.putExtra(JftConstants.JUN_FU_TONG_PRICE, mPrice);
        startActivity(intent);
    }

    private void showProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.show();
        } else {
            mProgressDialog = ProgressDialog.show(PayTypeActivity.this, "", getString(R.string.channel_list), false, true, null);
        }
    }
    private double getCostTime(Date startDate, Date endDate) {
        double tomerValue=endDate.getTime() - startDate.getTime();
        return tomerValue/1000;
    }
}
